package com.example.util.mybatis;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.example.util.EnumUtils;

/**
 * Created by James.H.Fu on 2017/5/26.
 *
 * @author James.H.Fu
 */
public class IntEnumTypeHandler<E extends Enum<?> & com.example.util.BaseEnum> extends BaseTypeHandler<Enum> {
    private Class<E> clazz;

    public IntEnumTypeHandler(Class<E> enumType) {
        if (enumType == null) {
            throw new IllegalArgumentException("Type argument cannot be null");
        }

        this.clazz = enumType;
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Enum parameter, JdbcType jdbcType)
            throws SQLException {
        ps.setInt(i, ((com.example.util.BaseEnum) parameter).getValue());
    }

    @Override
    public E getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return EnumUtils.fromValue(clazz, rs.getInt(columnName));
    }

    @Override
    public E getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return com.example.util.EnumUtils.fromValue(clazz, rs.getInt(columnIndex));
    }

    @Override
    public E getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return EnumUtils.fromValue(clazz, cs.getInt(columnIndex));
    }
}
